package com.sgl.retrofitdemo.net;

import com.alibaba.fastjson.JSON;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * Created by sunqiyong on 2016/11/13.
 */

public class FastJsonConvertFactory extends Converter.Factory {
    public static FastJsonConvertFactory create() {
        return new FastJsonConvertFactory();
    }
    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new FastJsonResponseBodyConverter<>(type);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return new FastJsonRequestBodyConverter<>();
    }

    @Override
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        return new QueryStringConverter<>();
    }

    public static class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

        private Type mType;

        public FastJsonResponseBodyConverter(Type type) {
            this.mType = type;
        }

        @Override
        public T convert(ResponseBody value) throws IOException {
            return JSON.parseObject(value.string(), mType);
        }
    }

    public static class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {

        @Override
        public RequestBody convert(T value) throws IOException {
            return RequestBody.create(MediaType.parse("application/json"), JSON.toJSONString(value));
        }
    }

    public static class QueryStringConverter<T> implements Converter<T, String> {

        @Override
        public String convert(T value) throws IOException {
            return null;
        }
    }
}
